package com.example.quanxian2.demo1.filter;

import com.example.quanxian2.demo1.VO.UserFilterVO;
import com.example.quanxian2.demo1.domain.User;
import com.example.quanxian2.demo1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static java.lang.Integer.valueOf;

//@WebFilter("/*")
public class QuanxianFilter implements Filter {
    @Autowired
    private UserService userService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
        //得到当前url
        String url = request.getRequestURI();
        //得到当前资源有权限的用户id
        List<UserFilterVO> list= userService.selectUserResource(url);
        //得到当前用户
        User user =(User) request.getSession().getAttribute("user");

        Integer userId = null;
        //如果用户登录了，得到其id
        if(user != null) {
            userId = user.getUserId();
        }
        if(userId == null){
            userId =valueOf(request.getParameter("userId"));
        }


        if (list ==null){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
        for (int x =0;x<list.size() ;x++){

            if (list.get(x).getUserId().equals(userId)){
                filterChain.doFilter(request, response);
                return;
            }
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
    }
}
